package cn.tedu.charging.order.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

//RabbitMq配置类
@Slf4j
@Configuration
public class RabbitMQConfig {
    //Order正常的Queue
    public static final String ORDER_QUEUE = "order.queue";
    //Order正常的Exchange
    public static final String ORDER_EXCHANGE = "order.exchange";
    //Order正常的routing_Key
    public static final String ROUTING_KEY = "order.router.key";
    //Order死信队列Exchange
    public static final String ORDER_DEAD_LETTER_EXCHANGE="order.dead.letter.exchange";
    //死信Exchange 和 死信Queue 绑定的Routing-Key
    public static final String ROUTING_DEAD_LETTER_KEY="order.dead.letter.routing.key";
    //死信队列的Queue
    public static final String ORDER_DEAD_LETTER_QUEUE = "order.dead.letter.queue";


    /**
     * 定义订单队列
     * @return
     */
    @Bean
    public Queue orderQueue() {
        Map<String,Object> args = new HashMap<>();
        args.put("x-dead-letter-exchange",ORDER_DEAD_LETTER_EXCHANGE);
        args.put("x-dead-letter-routing-key",ROUTING_DEAD_LETTER_KEY);
        //存活时间(ms)==> 60s
        Integer TTL = 5*60*1000;
        args.put("x-message-ttl",TTL);
        //惰性队列,在消息很多的时候,存到磁盘里,避免消息积压,占内存
        args.put("x-queue-mode","lazy");
        Boolean durable = true;

        //name 队列名称
        //durable 是否持久化 true重启后数据不会丢失
        //exclusive 是否独占队列
        //autoDelete 是否自动删除 true 临时队列  长时间不用就干掉 (队列里最后一条消息被消费了,队列会被自动删除)
        return new Queue(ORDER_QUEUE,durable,true,false,args);
    }

    /**
     * 定义订单Exchange 交换机
     * @return
     */
    @Bean
    public TopicExchange orderTopicExchange() {
        return new TopicExchange(ORDER_EXCHANGE);
    }

    /**
     * 把订单队列绑定到订单交换机上
     * @return
     */
    @Bean
    public Binding orderBinding() {
        return BindingBuilder
                .bind(orderQueue())
                .to(orderTopicExchange()).with(ROUTING_KEY);
    }

    //定义死信队列Exchange
    @Bean
    public TopicExchange deadLetterExchange(){
        return new TopicExchange(ORDER_DEAD_LETTER_EXCHANGE,true,false);
    }

    //定义死信队列的Queue
    @Bean
    public Queue deadLetterQueue(){
        return new Queue(ORDER_DEAD_LETTER_QUEUE,true,false,false);
    }

    //将死信队列Exchange与Queue
    @Bean
    public Binding deadLetterBinding(){
        return BindingBuilder
                .bind(deadLetterQueue())
                .to(deadLetterExchange())
                .with(ROUTING_DEAD_LETTER_KEY);
    }

}
